<?php

namespace App\Models\Schedule;

use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class ScheduleUserModel extends BaseModel
{
    use KfSoftDeletes;

    protected $table = "schedule_users";

    protected $fillable = [
        'shopId',
        'userId',
        'date',
        'ruleId',
        'ruleName',
        'ruleStart',
        'ruleEnd',
        'type',
        'color',
        'isDeleted',
    ];

    const TYPE_SINGLE  = 1;
    const TYPE_COMBINE = 2;
    const TYPE_CYCLE   = 3;

    const TYPE_DEL = 99; // 删除用

    const TYPE_TEXT = [
        self::TYPE_SINGLE  => '单次排班',
        self::TYPE_COMBINE => '组合排班',
        self::TYPE_CYCLE   => '周期排班',
    ];

    public static function add(
        int $userId,
        int $shopId,
        int $date,
        int $ruleId,
        string $ruleName,
        string $ruleStart,
        string $ruleEnd,
        int $type,
        string $color
    ) {
        return self::query()->create([
            'userId'    => $userId,
            'shopId'    => $shopId,
            'date'      => $date,
            'ruleId'    => $ruleId,
            'ruleName'  => $ruleName,
            'ruleStart' => $ruleStart,
            'ruleEnd'   => $ruleEnd,
            'type'      => $type,
            'color'     => $color,
        ]);
    }

    public static function clear(int $userId, int $shopId, int $start, int $end)
    {
        $result = self::query()
                     ->where('userId', $userId)
                     ->where('shopId', $shopId)
                     ->where('date', '>=', $start)
                     ->where('date', '<=', $end)
                     ->get();

        if ($result->count()) {
            self::query()->whereIn('id', $result->pluck('id'))->update(['isDeleted' => 1]);
        }

        return $result;
    }

    public function scheduleRemindSwitchRel(): HasMany
    {
        return $this->hasMany(ScheduleRemindSwitchModel::class, "userId", "userId");
    }
}
